package com.iteye.trafficRecorder;

import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;

public class SettingFragment extends Fragment implements ResponseListener {
	
	private EditText txtWebService;
	
	private Spinner gpsRecordTimer;
	
	private CheckBox chkStorelocal;
	
	private MainActivity _this;
	
	private DatabaseHelper dbHelper;
	
	private Setting setting;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.layout_setting, container);
	 	return view;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		_this = (MainActivity)getActivity();
		dbHelper = _this.getdb();
		setting = new Setting(_this);
		
		txtWebService = (EditText)_this.findViewById(R.id.txt_web_service);
		txtWebService.setText(setting.getWebServiceAddress());
		
		Resources res = getResources();
		gpsRecordTimer = (Spinner)_this.findViewById(R.id.gpsRecordTimer);
		ArrayAdapter<String> sampleAdapter = new ArrayAdapter<String>(
				_this, android.R.layout.simple_spinner_item, res.getStringArray(R.array.gps_record_options));
		gpsRecordTimer.setAdapter(sampleAdapter);
		final String[] optionValus = res.getStringArray(R.array.gps_record_options_values);
		gpsRecordTimer.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				setting.setGpsRecordsecond(Integer.parseInt(optionValus[position]));
			}

			public void onNothingSelected(AdapterView<?> parent) {}
			
		});
		int gpsRecordsecond = setting.getGpsRecordsecond();
		for (int i = 0; i < optionValus.length; i++) {
			if (gpsRecordsecond == Integer.parseInt(optionValus[i])) {
				gpsRecordTimer.setSelection(i);
				break;
			}
		}
		
		chkStorelocal = (CheckBox)_this.findViewById(R.id.chkStorelocal);
		chkStorelocal.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				Log.d("test", "isChecked" + isChecked);
				setting.setStoreLocal(isChecked);
			}
		});
		chkStorelocal.setChecked(setting.isStoreLocal());
		
        Button btnSave = (Button)_this.findViewById(R.id.btn_save);
        btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setting.setWebServiceAddress(txtWebService.getText().toString());
				Toast.makeText(_this, R.string.save_success, Toast.LENGTH_SHORT).show();
			}
        });
        
        Button btnSend = (Button)_this.findViewById(R.id.btn_send);
        btnSend.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				List<MyLocation> locations = dbHelper.getLocations();
				for (MyLocation location : locations) {
					try {
						List<NameValuePair> params = WebService.initParams(WebService.dataType_location, location.getLocationId(), location.toXml());
						HttpClientHelper.asyncPostTextRequest(_this, setting.getWebServiceUrl(), params, SettingFragment.this, location);
					} catch (Exception e) {
						Log.e("LocationService", "Error in submit regist info!", e);
					}
				}
			}
        });
	}

	public void onResponseSuccess(HttpResponse response, Object result, Object tagObj) {
		MyLocation location = (MyLocation)tagObj;
		dbHelper.deleteLocation(location.getLocationId());
		Log.d("SettingFragment", "location send success");
	}

	public void onResponseFailed(HttpResponse response, Throwable error, Object tagObj) {
		Log.d("SettingFragment", "location send error:" + error);
	}
	
}
